<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="章节标题" prop="chapterTitle">
        <el-input
          v-model="queryParams.chapterTitle"
          placeholder="请输入章节标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属课程" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="请选择所属课程" clearable size="small">
          <el-option
            v-for="dict in courseOptions"
            :key="dict.courseId"
            :label="dict.courseName"
            :value="dict.courseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内容类型" prop="contentType">
        <el-select v-model="queryParams.contentType" placeholder="请选择内容类型" clearable size="small">
          <el-option
            v-for="dict in contentTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['knowledge:chapter:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['knowledge:chapter:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['knowledge:chapter:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['knowledge:chapter:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chapterList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="chapterId" />
      <el-table-column label="章节标题" align="center" prop="chapterTitle" :show-overflow-tooltip='true'/>
      <el-table-column label="所属课程" align="center" prop="courseId" :formatter="courseFormat" :show-overflow-tooltip='true'/>
      <el-table-column label="内容类型" align="center" prop="contentType" :formatter="contentTypeFormat" />
      <el-table-column label="章节介绍" align="center" prop="chapterDescription" :show-overflow-tooltip='true'/>
      <el-table-column label="章节内容存储地址" align="center" prop="chapterPath" :show-overflow-tooltip='true'/>
      <el-table-column label="章节顺序号" align="center" prop="chapterSort" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip='true'/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['knowledge:chapter:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['knowledge:chapter:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程章节对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="章节标题" prop="chapterTitle">
          <el-input v-model="form.chapterTitle" placeholder="请输入章节标题" />
        </el-form-item>
        <el-form-item label="所属课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择所属课程" clearable size="small">
            <el-option
              v-for="dict in courseOptions"
              :key="dict.courseId"
              :label="dict.courseName"
              :value="dict.courseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容类型">
          <el-radio-group v-model="form.contentType">
            <el-radio
              v-for="dict in contentTypeOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="章节介绍" prop="chapterDescription">
          <el-input v-model="form.chapterDescription" placeholder="请输入章节介绍" />
        </el-form-item>
        <el-form-item label="章节内容" prop="chapterPath">

          <el-upload :on-success="handleAvatarSuccess" :action="field101Action" :before-upload="beforeUpload" :limit="1" >
            <input   v-model="form.chapterPath"  type="hidden" />
            <el-button  size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
          </el-upload>
          <!--图片-->
         <!-- <el-image v-if="form.chapterPath && form.contentType == 0" style="width: 200px;height: 200px;" :src="form.chapterPath">
          </el-image>-->
          <!--音频-->
          <audio v-if="form.chapterPath && form.contentType == 1" controls >
            <source :src="form.chapterPath" type="audio/mpeg">
          </audio>
          <!--视频-->
          <video v-if="form.chapterPath && form.contentType == 2" width="400" height="400" :src="form.chapterPath" controls="">
          </video>
        </el-form-item>
        <el-form-item label="章节顺序" prop="chapterSort">
          <el-input v-model="form.chapterSort" placeholder="请输入章节顺序号" />
        </el-form-item>
        <el-form-item label="章节备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChapter, getChapter, delChapter, addChapter, updateChapter, exportChapter,getAllCourse } from "@/api/knowledge/chapter";
import {getAllCategory} from "@/api/knowledge/course";

export default {
  name: "Chapter",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程章节表格数据
      chapterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 内容类型：0图文1音频2视频字典
      contentTypeOptions: [],
      // 课程字典
      courseOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chapterTitle: null,
        courseId: null,
        contentType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      field101Action: process.env.VUE_APP_BASE_API+'/common/upload',
      field101fileList: [],
    };
  },
  created() {
    this.getList();
    this.getDicts("content_type").then(response => {
      this.contentTypeOptions = response.data;
    });
    this.getAllCourse().then(response => {
      this.courseOptions = response.data;
    });
  },
  methods: {
    /** 查询课程章节列表 */
    getList() {
      this.loading = true;
      listChapter(this.queryParams).then(response => {
        this.chapterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 内容类型：0图文1音频2视频字典翻译
    contentTypeFormat(row, column) {
      return this.selectDictLabel(this.contentTypeOptions, row.contentType);
    },
    //课程数据处理
    courseFormat(row, column) {
      var datas = this.courseOptions;
      var value = row.courseId;
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].courseId == ('' + value)) {
          actions.push(datas[key].courseName);
          return true;
        }
      })
      return actions.join('');
      // return this.selectDictLabel(data, row.categoryId);
    },
    /** 查询课程 */
    getAllCourse() {
      getAllCourse().then(response => {
        this.courseOptions = response;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        chapterId: null,
        chapterTitle: null,
        courseId: null,
        contentType: 0,
        chapterDescription: null,
        chapterPath: null,
        chapterSort: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.chapterId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程章节";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const chapterId = row.chapterId || this.ids
      getChapter(chapterId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课程章节";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.chapterId != null) {
            updateChapter(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChapter(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const chapterIds = row.chapterId || this.ids;
      this.$confirm('是否确认删除课程章节编号为"' + chapterIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delChapter(chapterIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有课程章节数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportChapter(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleAvatarSuccess(res, file) {
      this.form.chapterPath = res.url;
    },
    // 上传预处理
    beforeUpload(file) {
      //this.uploadAction();
      const isLt2M = file.size / 1024 / 1024 < 50;

      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 50MB!');
      }
      var FileExt = file.name.replace(/.+\./, "");
      if(this.form.contentType == 0){
        if (['jpg','png','txt','pdf','doc','xlsx','docx'].indexOf(FileExt.toLowerCase()) === -1){
          this.$message({
            type: 'error',
            message: '请上传后缀名为jpg、png、txt、pdf、doc、docx、xlsx的附件！'
          });
          return false;
        }
      }
      if(this.form.contentType == 1){
        if (['MP3'].indexOf(FileExt.toLowerCase()) === -1){
          this.$message({
            type: 'error',
            message: '音频频只能上传MP3格式！'
          });
          return false;
        }
      }

      if(this.form.contentType == 2){
        if (["mp4"].indexOf(FileExt.toLowerCase()) === -1){
          this.$message({
            type: 'error',
            message: '视频只能上传MP4格式！'
          });
          return false;
        }
      }
      return isLt2M;
    },
  }
};
</script>
